package proj.unions.game;

import org.cocos2dx.lib.Cocos2dxActivity;
import org.json.JSONObject;

import proj.unions.general.GameView;
import proj.unions.general.L;
import proj.unions.general.OnMyCallBack;
import proj.unions.general.OnMyClickedListener;
import proj.unions.general.SCDialog;
import proj.unions.general.SuperTools;
import proj.unions.general.Template_Page;
import proj.unions.general.Text;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.ViewGroup.LayoutParams;
import android.widget.RelativeLayout;

import com.cylt.dbz.R;
import com.testin.agent.TestinAgent;

public class MainActivity  extends Cocos2dxActivity {
	
	private class PageData
	{
		PageData(int _pageIndex, Template_Page _pageClass, String _pageBG)
		{
			pageIndex = _pageIndex;
			pageClass = _pageClass;
			pageLayout = null;
			pageBG = _pageBG;
		}
		int pageIndex;
		Template_Page pageClass;
		RelativeLayout pageLayout;
		String pageBG;
	}
	
	protected static MainActivity mActivity = null;
	private static RelativeLayout mRelativeLayout = null;
	
	public static String gAccount = "";//账户Id
	public static String gPassword = "888888";//密码(默认888888)
	
	private int mWidth = 0;
	private int mHeight = 0;
	
	public final static int S_ShowPic = 1;
	public final static int S_UpdateRes = 2;
	public final static int S_Game = 3;
	
	private static boolean isExiting = false;
	private int mLastPageIndex = -1;
	private int mCurPageIndex = -1;
	
	private PageData mPageDatas[] = 
	{
		new PageData(S_ShowPic, new ShowPicture(), "bg.png"),
		new PageData(S_UpdateRes, new UpdateRes(), "bg.png"),
		new PageData(S_Game, new Game(), ""),
	};
	
	private Handler mHandler = new Handler()
	{
		public void dispatchMessage(android.os.Message msg)
		{
			switch(msg.what)
			{
				case 1001:
					setStatus(msg.arg1);
					break;
				default:
					break;
			}
			
		};
	};
	
	private OnMyCallBack mOnMyCallBack = new OnMyCallBack() {
		
		@Override
		public void onReceive(String arg0, int arg1, JSONObject json) {
			// TODO Auto-generated method stub
			//处理每个pageView返回的信息
			
		}
	};
	
	private void setStatus(int _index)
	{
		PageData preData = getPageData(mLastPageIndex);
		if(preData != null)
			removeLastView(preData);
		
		PageData data = getPageData(_index);
		if(data != null)
		{
			mLastPageIndex = mCurPageIndex;
			mCurPageIndex = _index;
			
			if(data.pageIndex == S_Game)
			{
				continuteOnCreate();//如果是game那就完成父类初始化
				addViewToFrameLayout(mRelativeLayout);
			}
			addCurView(data);
			addPageBG(data);
			data.pageClass.onCreate(mActivity, data.pageLayout, mOnMyCallBack);	
		}
	}
	
	private PageData getPageData(int index)
	{	
		for(int i = 0; i < mPageDatas.length; i++)
		{
			if(index == mPageDatas[i].pageIndex)
				return mPageDatas[i];
		}
		return null;
	}
	
	private void addCurView(PageData data)
	{
		if(data.pageLayout == null)
			data.pageLayout = new RelativeLayout(mActivity);
		data.pageLayout.removeAllViews();
		mRelativeLayout.addView(data.pageLayout, new LayoutParams(mWidth, mHeight));
	}
	
	private void removeLastView(final PageData data)
	{
		if(data.pageLayout == null)
			return;
		SuperTools.delayAction(500, new OnMyCallBack() {
			
			@Override
			public void onReceive(String arg0, int arg1, JSONObject json) {
				// TODO Auto-generated method stub
				mActivity.runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						mRelativeLayout.removeView(data.pageLayout);
					}
				});
			}
		});
	}
	
	private void addPageBG(PageData data)
	{
		if(data == null || data.pageLayout == null || data.pageBG.equals(""))
			return;
		GameView bg = new GameView(mActivity, null, new String[]{data.pageBG});
		data.pageLayout.addView(bg, new LayoutParams(mWidth, mHeight));	
	}
	
	public static void exitGame()
	{
		if(isExiting)
			return;
		isExiting = true;
		
		Activity a = SuperTools.getInstance().getCurActivity();
		String title = a.getResources().getString(R.string.app_name);
		SCDialog.create(a, title, Text.getKey("Local_AskExitGame")/*"是否退出游戏?"*/, 
				Text.getKey("Local_Exit")/*"退出"*/, Text.getKey("Local_Cancel")/*"取消"*/, new OnMyClickedListener() {
			
			@Override
			public void onNegative(JSONObject data) {
				// TODO Auto-generated method stub
				//结束游戏释放资源
				SuperTools.getInstance().releaseGameRes();
			}
			
			@Override
			public void onPositive(JSONObject data) {
				// TODO Auto-generated method stub
				isExiting = false;
			}
			
		}).show();

	}

	public static void switchStatus(int status)
	{
		mActivity.mHandler.obtainMessage(1001, status, -1).sendToTarget();
	}
	
	public static int getCurPageIndex()
	{
		return mActivity.mCurPageIndex;
	}
	
	public static RelativeLayout getCurLayout()
	{
		PageData data = mActivity.getPageData(mActivity.mCurPageIndex);
		if(data != null)
			return data.pageLayout;
		return null;
	}
	
	public static void closeOverUi()
	{
		mActivity.closeOverUI();
	}
	
//====================================================================================================
	@Override
	public void onCreate(Bundle bundle) 
	{
		super.onCreate(bundle);
		mActivity = this;
		mWidth = SuperTools.getInstance().getWidth();
		mHeight = SuperTools.getInstance().getHeight();
		mRelativeLayout = new RelativeLayout(mActivity);
		mActivity.setContentView(mRelativeLayout, new LayoutParams(mWidth, mHeight));
		setStatus(S_ShowPic);
		
		ApplicationInfo appInfo = null;
		String appkey = "";
		int channelId = 0;
		//读取manifest配置的AppKey和Channel ID
		try {
			appInfo = this.getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
			
			appkey = appInfo.metaData.getString("TESTIN_APPKEY");
			channelId = appInfo.metaData.getInt("TESTIN_CHANNEL");
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		TestinAgent.init(this, appkey, ""+channelId);
		TestinAgent.setLocalDebug( true ); //设置为true，则在log中打印崩溃堆栈
	}
	
	@Override
	public void onStart() {
		super.onStart();
		L.d("===========Main=onStart");
	}
	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		L.d("===========Main=onRestart");
	}
	
	@Override
	public void onStop() {
		super.onStop();
		L.d("===========Main=onStop");
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		L.d("===========Main=onPause");
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		L.d("===========Main=onResume");
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		L.d("===========Main=onDestroy");
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		L.d("===========Main=onNewIntent");
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			exitGame();
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		L.d("===========Main=onActivityResult");
	}
	
	@Override
	protected void onReceiveHomeKeyEvent(String reason) {
		// TODO Auto-generated method stub
		super.onReceiveHomeKeyEvent(reason);
		if((reason != null) && (!reason.isEmpty()))
	   	{
			if (reason.equals(SYSTEM_HOME_KEY)) 
			{
				//表示按了home键,程序到了后台
				
			}
			else if(reason.equals(SYSTEM_HOME_KEY_LONG))
			{
				//表示长按home键,显示最近使用的程序列表
				
			}
	   	}
	}
	
}
